package yannan.voiplock4ble.fragment;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.ScrollView;
import android.widget.TextView;

import com.nikhilpanju.recyclerviewenhanced.RecyclerTouchListener;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import yannan.voiplock4ble.R;
import yannan.voiplock4ble.SearchLockActivity;
import yannan.voiplock4ble.adapter.LockListAdapter;
import yannan.voiplock4ble.adapter.base.RecyclerViewBaseAdapter;
import yannan.voiplock4ble.base.Content;
import yannan.voiplock4ble.base.LockBaseFragment;
import yannan.voiplock4ble.base.MyApplication;
import yannan.voiplock4ble.bean.CommonResponse;
import yannan.voiplock4ble.bean.LockBean;
import yannan.voiplock4ble.bean.LockBeanDao;
import yannan.voiplock4ble.db.DaoUtils;
import yannan.voiplock4ble.db.MyDBHelper;
import yannan.voiplock4ble.db.daomanager.LockBeanDaoManager;
import yannan.voiplock4ble.net.NetUtils;
import yannan.voiplock4ble.net.base.NetworkCallBack;
import yannan.voiplock4ble.utils.PopShowUtils;
import yannan.voiplock4ble.utils.ToastUtils;
import yannan.voiplock4ble.view.MyDecoration;
import yannan.voiplock4ble.view.RecyclerSupportViewEmpty;
import yannan.voiplock4ble.view.SlowSwipeRefreshLayout;

/**
 * 说明：门锁列表页面
 * 作者：mainTel
 * 时间：2016/11/23 09:17
 * 备注：
 */
@Content(R.layout.fragment_lock_list)
public class LockListFragment extends LockBaseFragment implements SwipeRefreshLayout.OnRefreshListener, RecyclerViewBaseAdapter.OnItemClickListener, View.OnClickListener {
    @Bind(R.id.rl_lock_list)
    RecyclerSupportViewEmpty rl_lock_list;
    @Bind((R.id.rl_lock_list_empty_view))
    ScrollView rl_lock_list_empty_view;
    @Bind(R.id.lv_lock_record_empty_textview)
    TextView rl_lock_list_empty_textview;
    @Bind(R.id.swip_refresh)
    SlowSwipeRefreshLayout swip_refresh;
    LockListAdapter adapter;
    RecyclerTouchListener onTounchListener;

    @Override
    public void initdata() {
        adapter = new LockListAdapter(new ArrayList<LockBean>(), mContext);
        rl_lock_list.setLayoutManager(new LinearLayoutManager(mContext));
        rl_lock_list.addItemDecoration(new MyDecoration(mContext,
                MyDecoration.VERTICAL_LIST));
        rl_lock_list.setEmptyView(rl_lock_list_empty_view);
        rl_lock_list.setAdapter(adapter);

        swip_refresh.setOnRefreshListener(this);
        adapter.setOnItemClickListener(this);
        onTounchListener = new RecyclerTouchListener(mainActivity, rl_lock_list);
        onTounchListener.setSwipeOptionViews(R.id.tv_del, R.id.tv_edit)
                .setSwipeable(R.id.rowFG, R.id.rowBG, new RecyclerTouchListener.OnSwipeOptionsClickListener() {
                    @Override
                    public void onSwipeOptionClicked(int viewID, int position) {

                    }
                });
        rl_lock_list.addOnItemTouchListener(onTounchListener);
        rl_lock_list_empty_textview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                swip_refresh.setRefreshing(true);
                getLockList();
            }
        });
    }

    @Override
    public void initView() {

    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("LockListFragment");
        if (mainActivity.lockBeanList != null && mainActivity.lockBeanList.size() != 0) {
            adapter.upDate(mainActivity.lockBeanList);
        } else {
            getLockList();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("LockListFragment");
    }

    /**
     * 获取门锁列表
     */
    private void getLockList() {
        //先从本地获取吧
        List<LockBean> lockBeans = DaoUtils.getDao(LockBeanDaoManager.class).getQueryBuilder()
                .where(LockBeanDao.Properties.UserId.eq(MyApplication.getInterface().userBean.userId))
                .build().list();
        adapter.upDate(lockBeans);
        if (lockBeans.size() == 0) {
            NetUtils.getNetworkService().getLockList(MyApplication.getInterface().userBean.userId)
                    .enqueue(new NetworkCallBack<List<LockBean>>() {
                        @Override
                        public void onSuc(List<LockBean> resBody) {
                            if (swip_refresh.isRefreshing())
                                swip_refresh.setRefreshing(false);
                            if (resBody != null) {
                                for (LockBean lockBean : resBody) {
                                    lockBean.userId = MyApplication.getInterface().userBean.userId;
                                }
                                mainActivity.lockBeanList = resBody;
                                adapter.upDate(resBody);
                                DaoUtils.getDao(LockBeanDaoManager.class).deleteAll();
                                DaoUtils.getDao(LockBeanDaoManager.class).insertList(resBody);
                            }
                        }

                        @Override
                        public void onFail(String msg) {
                            // TODO: 2016/11/29 无数据
                            if (swip_refresh.isRefreshing())
                                swip_refresh.setRefreshing(false);
                        }
                    });
        } else {
            mainActivity.lockBeanList = lockBeans;
        }
        if (swip_refresh.isRefreshing())
            swip_refresh.setRefreshing(false);
    }

    @Override
    public void onRefresh() {
        getLockList();
    }

    @Override
    public void onItemClick(View view, int poi) {
        // TODO: 2016/11/23 切换页面
        final LockBean lockBean = adapter.getItemByPosition(poi);
        if (lockBean != null) {
            switch (view.getId()) {
                case R.id.tv_edit:
                    PopShowUtils.editLockName(mContext, lockBean, new PopShowUtils.IOnEditName() {
                        @Override
                        public void onChange(String msg) {
                            if (mainActivity.lockBeanNow != null)
                                if (lockBean.lockserialId.equals(mainActivity.lockBeanNow.lockserialId))
                                    mainActivity.lockBeanNow.lockName = msg;
                            LockBean bean = MyDBHelper.getLockBean(lockBean.lockserialId);
                            if (bean != null) {
                                bean.lockName = msg;
                                MyDBHelper.insertLockBean(bean);
                            }
                            getLockList();
                        }
                    });
                    break;
                case R.id.tv_del:
                    PopShowUtils.showCommonDialog(mContext, "确定要删除锁" + lockBean + "么？"
                            , "取消", "确定", true, new PopShowUtils.IDialogCommonListener() {
                                @Override
                                public void onClick(int direction) {
                                    if (direction == 0) {
                                        unBindLock(lockBean);
                                        if(MyApplication.getInterface().mConnectLock != null
                                                && MyApplication.getInterface().mConnectLock.lockserialId.equals(lockBean.lockserialId)){
                                            mainActivity.mBleService.disConnect();
                                        }
                                    }
                                }
                            });
                    break;
                case R.id.rowFG:
                    mainActivity.lockBeanNow = lockBean;
                    mainActivity.changeMenu(R.id.tv_lock_record);
                    break;
            }
        }

    }

    /**
     * 解绑门锁
     *
     * @param lockBean
     */
    private void unBindLock(final LockBean lockBean) {
        try {
            boolean b = MyDBHelper.delLockBean(lockBean.lockserialId);
            if (b) { //删除成功
                if (mainActivity.lockBeanNow != null)
                    if (lockBean.lockserialId.equals(mainActivity.lockBeanNow.lockserialId)) {
                        mainActivity.lockBeanNow = null;
                    }
                unBindLockNet(lockBean);
            } else { //删除失败
                ToastUtils.showToast(mContext, "解绑失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            //刪除失敗
            ToastUtils.showToast(mContext, "解绑失败");
        }
    }

    /**
     * @param lockBean
     */
    private void unBindLockNet(LockBean lockBean) {
        NetUtils.getNetworkService().unBindLock(lockBean.lockserialId, MyApplication.getInterface()
                .userBean.userId).enqueue(new NetworkCallBack<CommonResponse>() {
            @Override
            public void onSuc(CommonResponse resBody) {
                if (resBody.returnValue.equals("1")) {
                    ToastUtils.showToast(mContext, "解绑成功");

                    getLockList();
                } else {
                    ToastUtils.showToast(mContext, "解绑失败");
                }
            }

            @Override
            public void onFail(String msg) {
                ToastUtils.showToast(mContext, "解绑失败");
            }
        });
    }

    @OnClick({R.id.iv_add_lock})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_add_lock:
                mainActivity.isAutoConnect = true;
                Intent intent = new Intent(mContext, SearchLockActivity.class);
                startActivity(intent);
                break;
        }
    }
}
